package com.wuseguang.springcloud.util;

import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Excel下载工具类
 * @author zmc
 * @since 2019-12-10
 */
public class ExcelDownloadUtils {

    private static Logger logger = LoggerFactory.getLogger(ExcelDownloadUtils.class);

    /**
     * 下载excel
     * @param response
     * @param os
     * @param fileName excel名字
     * @throws IOException
     */
    public static void downloadExcel(HttpServletResponse response, ByteArrayOutputStream os, String fileName)
            throws IOException {

        logger.info("downloadExcel, fileName=" + fileName);

        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);

        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        ServletOutputStream out = response.getOutputStream();

        try{
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            //复制execl
            IOUtils.copy(bis, bos);
            bos.flush();
        } catch(Exception ex) {
            logger.error("export to excel failed,filename=" + fileName, ex);
        }
    }

    public static void downloadExcel(HttpServletRequest request,
                                     HttpServletResponse response,
                                     String filePath,
                                     String fileName){
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("classpath:"+filePath);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Credentials","true");
        response.setHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");

        try {
            String encodeName = new String((fileName).getBytes(),"iso-8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+encodeName);
            inputStream = resource.getInputStream();
            servletOutputStream = response.getOutputStream();
            IOUtils.copy(inputStream, servletOutputStream);
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(inputStream != null){
                    inputStream.close();
                }
                if(servletOutputStream != null){
                    servletOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
